<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  useDialog
} from 'naive-ui'
import { h, onActivated, onMounted, reactive, ref, onBeforeUnmount, onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import type { RoleModel } from '@/api/role'
import type { HttpResponsePagination } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import renderStatus from '@/components/renderStatus'
import { useRouter } from 'vue-router'
import upIcon from '@/assets/images/up_logo.png?url'
import lowIcon from '@/assets/images/low_logo.png?url'
import topIcon from '@/assets/images/top_logo.png?url'

const message = useMessage()
const router = useRouter()
const dialog = useDialog()

onBeforeUnmount(() => {
  dialog.destroyAll()
})
onDeactivated(() => {
  window.removeEventListener('keyup', keyUpDown, false)
  dialog.destroyAll()
})

onActivated(() => {
  if (window.flags.flushRole) {
    queryTableData()
    window.flags.flushRole = false
  }
})

const tableData = ref<RoleModel[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
const columns: DataTableColumns<RoleModel> = [
  {
    fixed: 'left',
    title: '排序',
    key: 'orderIndex',
    render: (_, i) => {
      return ++i + (paginationReactive.page - 1) * paginationReactive.pageSize
    },
    align: 'center',
    width: '5rem',
  },
  {
    title: '角色名称',
    key: 'roleName',
    align: 'center',
    width: '20rem',
  },
  {
    title: '状态',
    key: 'roleStatus',
    align: 'center',
    width: '20rem',
    render(row) {
      return renderStatus(row.roleStatus)
    }
  },
  {
    title: '创建人',
    key: 'createdByName',
    align: 'center',
    width: '20rem',
  },
  {
    title: '备注',
    key: 'notes',
    align: 'center',
    width: '40rem',
    ellipsis: {
      tooltip: {
        maxWidth: 400
      }
    }
  },
  {
    title: '操作',
    key: 'cz',
    align: 'center',
    width: '40rem',
    fixed: 'right',
    render(e) {
      return h('div', null, [
        h(
          NButton,
          {
            quaternary: true,
            color: '#6CB187',
            style: 'margin-right: 6px',
            onClick: () => {
              router.push({
                name: 'editRole',
                params: {
                  id: e.id
                }
              })
            }
          },
          {
            default: () => '编辑'
          }
        ),
        h(
          NButton,
          {
            quaternary: true,
            color: '#6CB187',
            onClick: () => {
              router.push({
                name: 'bindRole',
                params: {
                  id: e.id
                }
              })
            }
          },
          {
            default: () => '反查'
          }
        ),
        h(
          NButton,
          {
            quaternary: true,
            color: '#FD4A29',
            onClick: () => {
              dialog.warning({
                title: '警告',
                content: '是否确定删除?',
                positiveText: '确定',
                negativeText: '取消',
                onPositiveClick: () => {
                  sendRequest({
                    module: 'role',
                    api: 'delete',
                    override: {
                      data: [e.id]
                    }
                  })
                    .then(([error, res]) => {
                      if (error) return message.error(error.message)
                      if (res.code !== 0) return message.error(res.msg)
                      queryTableData()
                      message.success(res.msg)
                    })
                    .catch(() => {
                      message.error('删除失败!')
                    })
                }
              })
            }
          },
          {
            default: () => '删除'
          }
        ),
        h(
          'img',
          {
            style: {
              margin: '3px 15rem',
              width: '16rem',
              height: '16rem',
              cursor: 'pointer',
              display: e.sortIndex ? 'inline' : 'none'
            },
            src: upIcon,
            onClick: () => handleUp(e.id)
          },
          {
            default: () => upIcon
          }
        ),
        h(
          'img',
          {
            style: {
              margin: '3px 15rem',
              width: '16rem',
              height: '16rem',
              cursor: 'pointer',
              display: e.sortIndex + 1 != paginationReactive.itemCount ? 'inline' : 'none'
            },
            src: lowIcon,
            onClick: () => handleLow(e.id)
          },
          {
            default: () => lowIcon
          }
        ),
        h(
          'img',
          {
            style: {
              margin: '3px 15rem',
              width: '16rem',
              height: '16rem',
              cursor: 'pointer',
              display: e.sortIndex ? 'inline' : 'none'
            },
            src: topIcon,
            onClick: () => handleTop(e.id)
          },
          {
            default: () => topIcon
          }
        )
      ])
    }
  }
]

const searchName = ref('')
const tableLoading = ref(false)
const queryTableData = async (reset = false) => {
  tableLoading.value = true
  if (reset) paginationReactive.page = 1
  const [error, res] = await sendRequest<HttpResponsePagination<RoleModel>>({
    module: 'role',
    api: 'list',
    override: {
      params: {
        name: searchName.value || null,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false

  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list
}


//上移
const handleUp = async (val: any) => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'role',
    api: 'upItem',
    override: {
      params: {
        id: val
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.data)
  queryTableData(true)
}

//下移
const handleLow = async (val: any) => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'role',
    api: 'downItem',
    override: {
      params: {
        id: val
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.data)
  queryTableData(true)
}

//置顶
const handleTop = async (val: any) => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'role',
    api: 'topItem',
    override: {
      params: {
        id: val
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.data)
  queryTableData(true)
}

const keyUpDown = (e: any) => e.key == 'Enter' && queryTableData(true)
onMounted(() => {
  window.addEventListener('keyup', keyUpDown, false)
  queryTableData()
})
</script>

<template>
  <TableView class="role">
    <template #form>
      <NSpace align="center" style="margin-bottom: 14rem">
        <NSpace align="center">
          角色名称：
          <NInput placeholder="请输入" v-model:value="searchName" clearable style="width: 150rem" />
        </NSpace>
        <NButton style="width: 78rem" color="#6CB187" ghost @click="queryTableData(true)" :disabled="tableLoading"
          :loading="tableLoading">
          查询
        </NButton>
        <NButton color="#5FB17F" style="width: 78rem" @click="() => {
          router.push({
            path: router.currentRoute.value.path + '/add'
          })
        }
          ">
          新增
        </NButton>
      </NSpace>
    </template>
    <template #table="props">
      <n-data-table v-bind="props" :data="tableData" :columns="columns" :loading="tableLoading" size="small"
        :bordered="false" />
    </template>
    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
</template>

<style lang="scss" scoped>
.role {
  padding: 29rem 20rem 42rem 30rem;
  color: rgba(0, 0, 0, 0.85);
}
</style>
